<?php
/**
 * 站长表控制器
 */

namespace app\admin\controller;

use app\common\model\AdminMoneyRecord;
use think\Request;
use app\common\model\UserAgent;
use Think\Db;

use app\common\validate\UserAgentValidate;

class UserAgentController extends Controller
{

    //列表
    public function index(Request $request, UserAgent $model)
    {
        $param = $request->param();
        $model  = $model->scope('where', $param);
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['ID','用户名','头像','手机号','qq','邮箱','金币余额','创建时间',];
            $body   = [];
            $data   = $model->select();
            foreach ($data as $item) {
                $record       = [];
                $record['id'] = $item->id;
                $record['username'] = $item->username;
                $record['avatar'] = $item->avatar;
                $record['mobile'] = $item->mobile;
                $record['qq'] = $item->qq;
                $record['email'] = $item->email;
                $record['user_money'] = $item->user_money;
                $record['status'] = $item->status_text;
                $record['create_time'] = $item->create_time;

                $body[]       = $record;
            }
            return $this->exportData($header, $body, 'user_agent-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query'=>$request->get()]);
        //关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, UserAgent $model, UserAgentValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理头像上传
            $attachment_avatar = new \app\common\model\Attachment;
            $file_avatar       = $attachment_avatar->upload('avatar');
            if ($file_avatar) {
                $param['avatar'] = $file_avatar->url;
            } else {
                return error($attachment_avatar->getError());
            }

            $result = $model::create($param);

            $url = URL_BACK;
            if(isset($param['_create']) && $param['_create']==1){
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功',$url) : error();
        }

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, UserAgent $model, UserAgentValidate $validate)
    {

        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理头像上传
            if (!empty($_FILES['avatar']['name'])) {
                $attachment_avatar = new \app\common\model\Attachment;
                $file_avatar       = $attachment_avatar->upload('avatar');
                if ($file_avatar) {
                    $param['avatar'] = $file_avatar->url;
                }
            }

            $result = $data->save($param);
            return $result ? success() : error();
        }

        $this->assign([
            'data' => $data,
        ]);

        return $this->fetch('add');
    }

    //删除
    public function del($id, UserAgent $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //userMoney
    public function userMoney(Request $request, UserAgent $model)
    {
        $param = $request->param();
        if($request->isPost())
        {
            $money = $param['money'];
            $zid = $param['zid'];
            $remark = $param['remark'];
            //根据站长ID查找站长的信息
            $zinfo = $model::get($zid);
            //计算站长累加后的金额
            $zAll = $zinfo['user_money']+$money;
            if($money>0)
            {
                $describe = "管理员已把站长(".$zinfo['username'].")，的金额增加".$money."元，总金额为".$zAll."元";
            }else if($money<0){
                $describe = "管理员已把站长(".$zinfo['username'].")，的金额扣除".$money."元，总金额为".$zAll."元";
            }

            $dataUpdate = [
                'amount'=>$money,
                'note'=>$describe,
                'create_time'=>time(),
            ];

            $remark = [
                'user_money'=>$zAll,
                'remark'=>$remark
            ];

            // 启动事务
            Db::startTrans();
            try{

                $where['id'] = $zid;
                Db::table('user_agent')->where($where)->update($remark);
                Db::table('admin_money_record')->insert($dataUpdate);

                // 提交事务
                Db::commit();
                return json(["errorCode"=>200,"msg"=>"数据提交成功！"]);die;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["errorCode"=>401,"msg"=>"数据提交失败！"]);die;
            }
        }
    }

    //站长审核
    public function auditMaster(Request $request, UserAgent $model)
    {
        $param = $request->param();
        if($request->isPost())
        {
            //查找站长状态
            $id = $param['id'];
            $zStatus = UserAgent::find($id);

            $where['id'] = $id;
            $field = "status";
            if($zStatus['status']=="normal")
            {
                $data=[
                    'status'=>'hidden'
                ];
            }elseif ($zStatus['status']=="hidden"){
                $data=[
                    'status'=>'normal'
                ];
            }
            $res = UserAgent::update($data,$where,$field);
            if($res)
            {
                return json(["errorCode"=>200,"msg"=>"审核成功！"]);die;
            }else{
                return json(["errorCode"=>200,"msg"=>"审核失败！"]);die;
            }
        }
    }
}